6.9 How to support browser history in SPA

  1. Motivations
    • In SPA, data are exchanged between the client and the server, using AJAX.
    • The browser does not consider the AJAX data as a new page. Hence the back and forward buttons cannot be used, even though they are sometimes very convenient to use.
    • Simply put, logical pages in a SPA.
    • Any good idea?
  2. Try this - A pushState Example.
  3. How to support browser history - HTML5 history API
    • Read all in Manipulating the browser history.
    • Moving forward
    • Moving backword
    • Moving to a specific point in history
    • Adding and modifying history entries
      • history.pushState()
      • onpopstate
  4. Here is an example code that can be used for TRUQA.
    var logical_page_no = 0;
    $('#button-search-questions').click(function() {
        logical_page_no++;
        var stateObj = {logical_page_no:logical_page_no, page: 'MainPage', command:'SearchQuestions', 'search-terms': 'TRU'};
        history.pushState(stateObj, "SearchQuestions");
    
        // send ajax requrest
        ...
    });
    $(window).on('popstate', function(e) {
        if (e.originalEvent.state == null)
            logical_page_no = 0;;  // The initial page
        else {
            logical_page_no = e.originalEvent.state.logical_page_no;
    
            // send ajax request with the information stored in e.originalEvent.state
            //                          e.originalEvent.state.page, e.originalEvent.state.command, e.originalEvent.state['serarch-terms']
            ...
        }
    });
    

  5. Some review questions and learning outcomes